package com.uiao.activemq;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.Logger;

import javax.jms.*;

/**
 * 点对点消息接收端
 *
 * Created by uiao on 2018/3/10.
 */
public class QueueConsumer {

    private static Logger logger = Logger.getLogger(QueueConsumer.class);

    public static void main(String[] args) {
        ConnectionFactory connectionFactory;
        Connection connection = null;
        Session session;
        Destination destination;
        MessageConsumer messageConsumer;
        connectionFactory = new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
        try {
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // 需要接收端确认
            destination = session.createQueue("mq-queue");
            messageConsumer = session.createConsumer(destination);
            // 不使用监视器的情况
            /*while (true) {
                TextMessage textMessage = (TextMessage) messageConsumer.receive(1000); // 设置超时时间，超过不等待消息
                if (textMessage != null) {
                    logger.info("收到的消息：" + textMessage.getText());
                    textMessage.acknowledge();
                } else {
                    break;
                }
            }*/
            // 使用监视器的情况
            messageConsumer.setMessageListener(new MessageListener() {
                // 实现了一个监听器
                @Override
                public void onMessage(Message message) {
                    try {
                        TextMessage textMessage = (TextMessage) message;
                        //MqBean mqBean = (MqBean) ((ObjectMessage) message).getObject();
                        if (null != message) {
                            logger.info("收到的消息：" + textMessage.getText());
                        }
                        // 如果session设置为Session.CLIENT_ACKNOWLEDGE,要加上这一步
                        message.acknowledge();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
